#include "BasePlugin.h"

char* MESSAGE_BROADCAST_ENABLE = "messageBroadcastEnable";
char* MESSAGE_BROADCAST_DISABLE = "messageBroadcastDisable";
char* MESSAGE_RECEIVE = "messageReceive";

char* MSGTYPE_INCOMING_PRIVATE = "incoming_privateMessage";


BasePlugin::BasePlugin(){
	_broadcast_id = -1;
}

BasePlugin::~BasePlugin(){


}

void BasePlugin::Load(plugin_info_t* plugin_info){
	strcpy(plugin_info->guid, GetGUID()); 
	strcpy(plugin_info->name, GetName()); 
	strcpy(plugin_info->company, GetCompany()); 
	strcpy(plugin_info->version, GetVersion()); 
	strcpy(plugin_info->description, GetDescription());

	_home_directory = new char[strlen(plugin_info->config_directory)+1];
	strcpy(_home_directory, plugin_info->config_directory);
	_plugin_send = plugin_info->plugin_send; 
}

void BasePlugin::Unload(){
	delete[] _home_directory;
}


void BasePlugin::InitialLoad(){

}

void BasePlugin::FinalUnload(){

}


void BasePlugin::Start(){

}

void BasePlugin::Stop(){
	if (_broadcast_id != -1){
		DisableBroadcast();
	}
}


const char* BasePlugin::GetName(){
	return "Unnamed Plugin";
}
const char* BasePlugin::GetCompany(){
	return "Unknown Comapany";
}
const char* BasePlugin::GetVersion(){
	return "0.1b";
}
const char* BasePlugin::GetDescription(){
	return "Just Plugin";
}


int BasePlugin::Send(char* command, void* data){
	return _plugin_send(GetGUID(), command, data);
}

int BasePlugin::EnableBroadcast(){
	int result = 0;
	if (_broadcast_id == -1){
		message_broadcast_t	mbt;
		trillianInitialize(mbt);
		mbt.callback = broadCallback;
		mbt.data = this;
		result = _broadcast_id = Send(MESSAGE_BROADCAST_ENABLE, &mbt);
	}
	return result;
}

int BasePlugin::DisableBroadcast(){
	int result = 0;
	if (_broadcast_id != -1){
		message_broadcast_t	mbt;	
		trillianInitialize(mbt);
		mbt.broadcast_id = _broadcast_id;
		result =  Send(MESSAGE_BROADCAST_ENABLE, &mbt);
		_broadcast_id = -1;
	}
	return result;
}

int BasePlugin::OnBroadcast(int windowID, char *subwindow, char *event, message_t* msg){
	return 0;
}

int broadCallback(int windowID, char *subwindow, char *event, void *data, void *userData){
	BasePlugin* plugin = (BasePlugin*)userData;
	message_t* mbt = (message_t*)data;
	return plugin->OnBroadcast(windowID, subwindow, event, mbt);
}

int BasePlugin::CMDReceive(char* medium, int connection_id, char* name, char* type, char* text, int window_id, unsigned int time_stamp){
	message_t msg;
	trillianInitialize(msg);
	msg.medium = medium;
	msg.connection_id = connection_id;
	msg.name = name;
	msg.type = type;
	msg.text = text;
	msg.window_id = window_id;
	msg.time_stamp = time_stamp;
	return Send(MESSAGE_RECEIVE, &msg);
}

bool BasePlugin::IsIncomingPrivateMessage(message_t* msg){
	return (strequal(msg->type, MSGTYPE_INCOMING_PRIVATE));
}